
// 提取富文本中的图片地址
export function getImgSrc(richtext,num=3){
	let imgList =[];
	richtext.replace(/<img [^>]*src=[’"]([^’"]+)[^>]*>/g,(match, capture)=>{
		imgList.push(capture);
	});
	imgList=imgList.slice(0,num)
	return imgList;
}
// 封装高德通过ip获取省份接口
function getProvinceByIp(){
	return new Promise((resolve,reject)=>{
		uni.request({
			url:"https://restapi.amap.com/v3/ip?key=f07074afda554e0475810beea69ea72d",
			method:"GET",
			success(res) {
				let province = '';
				if(typeof(res.data.province) == 'string'){
					province = res.data.province
				}else{
					province = '未知区域'
				}
				resolve(province)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}
// 获取ip归属地
export function getProvince(){
	return new Promise(async (resolve,reject)=>{
		let fetchLock = false;
		let historyProvince = uni.getStorageSync("historyProvince");
		if(historyProvince){
			let needRefresh = Date.now() - historyProvince.time < 1000 * 60 * 60
			if(needRefresh){
				console.log("ip缓存",historyProvince.province)
				resolve(historyProvince.province)
				fetchLock = true;
			}
		}
		if(!fetchLock){
			getProvinceByIp().then(res=>{
				resolve(res)
				let obj = {
					province:res,
					time:Date.now()
				}
				uni.setStorageSync('historyProvince',obj)
			}).catch(err=>{
				reject(err)
			})
		}
	})
}

// 昵称封装
export function getUserNickName(user_id){
	if(Array.isArray(user_id) && user_id.length){
		let userInfo = user_id[0];
		return userInfo.nickname || userInfo.username || userInfo.mobile || '未知用户'
	}else{
		return '已注销用户'
	}
}

// 头像封装
export function getUserAvatar(user_id){
	if(Array.isArray(user_id) && user_id.length){
		let userInfo = user_id[0];
		return userInfo.avatar_file?.url ?? '/static/avatar.webp'
	}else{
		return '/static/avatar.webp'
	}
}